﻿using Abp.Authorization;
using Abp.Linq.Expressions;
using Abp.UI;
using Basefr.App;
using Basefr.App.Messages;
using Microsoft.AspNetCore.Mvc;
using Paas.App.Interface.MetaTables;
using Paas.App.Interface.MetaTables.Dtos;
using Paas.App.Interface.MetaTables.Messages;
using Paas.App.Interface.MetaViews.Dtos;
using Paas.App.Interface.MetaViews.Messages;
using Paas.Core;
using Paas.Core.Const.Enums;
using Paas.Core.Meta.Entities;
using Paas.Core.MetaTables.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Paas.App.MetaTables
{
    [Route("metaTables-metaTable")]

    [AbpAuthorize()]
    public class MetaTableAppService: AppService, IMetaTableAppService
    {
        private readonly IMainRepository<MetaTable, Guid> _metaTableRepo;
        private readonly IMainRepository<MetaObject,Guid> _metaObjectRepo;
        private readonly IMainRepository<MetaField, Guid> _metaFieldRepo;


        public MetaTableAppService(IMainRepository<MetaTable, Guid> metaTableRepo,IMainRepository<MetaObject,Guid> metaObjectRepo, IMainRepository<MetaField, Guid> metaFieldRepo)
        {
            _metaTableRepo = metaTableRepo;
            _metaObjectRepo = metaObjectRepo;
            _metaFieldRepo = metaFieldRepo;
        }

        #region 增改
        [HttpPost(nameof(SaveMetaTable))]
        public async Task<SaveMetaTableOutput> SaveMetaTable(SaveMetaTableInput input)
        {
            if (input == null) throw new UserFriendlyException("保存元对象信息失败：input为空！");
            var entity = ObjectMapper.Map<MetaTable>(input.Item);
            if (input.Item?.Id != null && input.Item?.Id != Guid.Empty)
            {
                //var uData = await _metaTableRepo.GetAsync(input.Item.Id);
                //if (uData == null) throw new UserFriendlyException("未找到需要更新的对象表格！");

                #region 需要更新的字段
                //uData.Label = input.Item.Label;
                //uData.Description = input.Item.Description;
                //uData.MetaGroup= input.Item.MetaGroup;
                #endregion

                await _metaTableRepo.UpdateAsync(entity); ;
                return new SaveMetaTableOutput();
            }

            //设置一些默认的值
            entity.MetaGroup = "default";
            entity.CurrentStatus ??= MetaStatus.New;
            //entity.IsPublic = true;

            await _metaTableRepo.InsertAsync(entity);

            return new SaveMetaTableOutput();
        }
        #endregion
        #region 查
        [HttpPost(nameof(SearchMetaTable))]
        public async Task<SearchMetaTableOutput> SearchMetaTable(SearchMetaTableInput input)
        {
            Expression<Func<MetaTable, bool>> predicate = p => true;
            if (!string.IsNullOrWhiteSpace(input.Name))
            {
                predicate = predicate.And(p => p.Name.Contains(input.Name.Trim()));
            }
            if (!string.IsNullOrWhiteSpace(input.Label))
            {
                predicate = predicate.And(p => p.Label.Contains(input.Label.Trim()));
            }
            //if (input.ApplicationId != null && input.ApplicationId != 0)
            //{
            //    predicate = predicate.And(p => p.ApplicationId == input.ApplicationId);
            //}
            if (!string.IsNullOrWhiteSpace(input.ObjectId))
            {
                predicate = predicate.And(p => p.ObjectId == input.ObjectId);
            }

            var result = await _metaTableRepo.GetAllListAsync(predicate);
            var res = result.OrderByDescending(p => p.SortNum).Skip(input.SkipCount).Take(input.MaxResultCount).ToList();
            var totalCount = result.Count();
            var resultItems = ObjectMapper.Map<List<MetaTableDto>>(res);
            return new SearchMetaTableOutput { Items = resultItems, TotalCount = totalCount };
        }
        /// <summary>
        /// 根据id查询单条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost(nameof(SearchSingle))]
        public async Task<QuerySingleOutput<MetaTableDto>> SearchSingle(QueryInput<Guid> input)
        {

            var result = await _metaTableRepo.FirstOrDefaultAsync(input.Id);
            var resultItem = ObjectMapper.Map<MetaTableDto>(result);

            return new QuerySingleOutput<MetaTableDto>() { Item=resultItem };
        }

        #endregion
        #region 删
        [HttpPost(nameof(DeleteMetaTable))]
        public async Task<DeleteMetaTableOutput> DeleteMetaTable(DeleteMetaTableInput input)
        {
            //await _metaTableRepo.
            await _metaTableRepo.DeleteAsync(input.Id);
            return new DeleteMetaTableOutput();
        }
        #endregion
    }
}
